<template>
  <div>
    <div :ref="'toolbar-' + _uid" class="toolbar"></div>
    <div :ref="'editor-' + _uid" class="text"></div>
  </div>
</template>

<script>
import E from "wangeditor";
export default {
  name: "editoritem",
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/uploadWang",
      baseUrl: process.env.VUE_APP_BASE_API,
      editor: null,
    };
  },
  mounted() {
    var that = this;
    // 确保之前的实例被销毁
    if (this.editor != null) {
      this.editor.destroy();
      this.editor = null;
    }
    // 创建编辑器
    // 使用 ref 创建编辑器
    this.editor = new E(
      this.$refs["toolbar-" + this._uid],
      this.$refs["editor-" + this._uid]
    );
    this.editor.config.uploadImgServer = this.uploadUrl;
    this.editor.config.uploadImgMaxSize = 10 * 1024 * 1024; // 2M
    this.editor.config.uploadImgAccept = [
      "jpg",
      "jpeg",
      "png",
      "gif",
      "bmp",
      "webp",
    ];
    this.editor.config.uploadFileName = "fileName";
    this.editor.config.menus = [
      "head",
      "bold",
      "fontSize",
      "fontName",
      "italic",
      "underline",
      "strikeThrough",
      "indent",
      "lineHeight",
      "foreColor",
      "backColor",
      "link",
      "list",
      "todo",
      "justify",
      "quote",
      "emoticon",
      "image",
      "video",
      "table",
      // 'code',
      "splitLine",
      "undo",
      "redo",
    ];
    this.editor.config.onchange = function (newHtml) {
      that.$emit("on-text-change", newHtml);
    };
    // 配置触发 onchange 的时间频率，默认为 200ms
    this.editor.config.onchangeTimeout = 500; // 修改为 500ms
    this.editor.config.uploadImgHooks = {
      // 上传图片之前
      before: function (xhr) {
      },
      // 图片上传并返回了结果，图片插入已成功
      success: function (xhr) {
      },
      // 图片上传并返回了结果，但图片插入时出错了
      fail: function (xhr, editor, resData) {

      },
      // 上传图片出错，一般为 http 请求的错误
      error: function (xhr, editor, resData) {
      },
      // 上传图片超时
      timeout: function (xhr) {
      },
      // 图片上传并返回了结果，想要自己把图片插入到编辑器中
      // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
      // customInsert: function(insertImgFn, result) {

      // }
    };
    this.editor.create();
  },
  beforeMount() {
    if (this.editor != null) {
      this.editor.destroy();
      this.editor = null;
    }
  },
  beforeDestroy() {
    // 销毁编辑器
    this.editor.destroy();
    this.editor = null;
  },
  methods: {
    initEditor() {
      this.editor.txt.html("");
    },
    setText(text) {
      if (text == undefined || text == null) {
        this.editor.txt.html("");
      } else {
        this.editor.txt.html(text);
      }
    },
  },
};
</script>

<style>
.toolbar {
  border: 1px solid #ccc;
}
.text {
  border: 1px solid #ccc;
  min-height: 300px;
}
</style>
